from flask import Blueprint, request, jsonify, current_app
from com import db
from com.util import Rep
import json
from urllib import response, request as req, parse as urlParse

searchPic = Blueprint('searchPic', __name__)


# 进行搜索
@searchPic.route('/searchPic', methods=['GET'])
def search():
    body = request.args.to_dict()
    requestOne = request
    searchUrl = ""
    searchType = body.get("searchType", 1)
    pageNum = body.get("pageNum", 1)
    pageSize = body.get("pageSize", 10)
    key = body.get("key", "")

    if key == "":
        return Rep.Ok(data=[])

    nowType = body.get("searchType")
    param = ''
    print("zheshi", nowType)
    # 1代表搜狗搜索 2代表百度搜索
    if searchType is not None and (searchType == 1 or searchType == '1'):
        searchUrl = current_app.urlList[0]
        param = {
            'query': key,
            'start': (int(pageNum) - 1) * int(pageSize)
        }
    else:
        searchUrl = current_app.urlList[1]
        param = {
            'word': key,
            'queryWord': key,
            'pn': pageNum,
            'rn': pageSize
        }

    # 进行搜索，并返回数据
    # 搜狗： query start
    # 百度：queryWord word pn rn
    searchUrl = searchUrl + '&' + urlParse.urlencode(param)
    data = toSearch(searchUrl, searchType)

    print("这是返回的结果", data)
    return jsonify(Rep.Ok(data=data))
    pass


def toSearch(url, type):
    result = []
    print("这是url", url)
    with req.urlopen(url) as f:

        if type == '1' or type == 1:

            # print("相应的请求头为", f.getCode())
            body_item = f.read().decode(encoding='GBK')
            body_item = json.loads(body_item)
            items = body_item['items']
            for i in items:
                result.append({
                    "pic_url": i['thumbUrl'],
                    "title": i['title']
                })
        else:
            body_item = f.read().decode(encoding='utf8')
            body_item = json.loads(body_item)
            items = body_item['data']
            for i in items:
                picUrl = i.get('thumbURL')
                if picUrl is None or picUrl == '':
                    continue
                result.append({
                    "pic_url": i.get('thumbURL'),
                    "title": i.get('fromPageTitleEnc', '')
                })
    return result


@searchPic.route("/selectAllUser")
def selectAllUser():
    userList = db.get_db_dict().execute("select * from user").fetchall()
    print("长度为", len(userList))
    for user in userList:
        print(user, "类型为", type(user))

    return jsonify({"list": userList, "status": 0})


@searchPic.route("/addOneUser", methods=['POST', 'PUT'])
def addOneUser():
    body = request.json
    print("请求体为", body)
    con = db.get_db()
    cur = con.cursor()

    try:
        cur.execute("insert into user (username, password) values (?, ?)", [body['username'], body['password']])
        con.commit()
    except Exception as e:
        print("出现了异常", e)
        return jsonify({"message": '新增失败'})
    return jsonify({"status": 0, "message": "新增完成"})
